package com.huwaiwai.zookeeper.demo01;

import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by huweiwei on 2017/4/7.
 */
@AllArgsConstructor
@NoArgsConstructor
public class SimpleServer implements Runnable {

    private int port;

    @Override
    public void run() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("server started");
            while (true) {
                Socket socket = serverSocket.accept();
                new Thread(new SimpleServerHandler(socket)).start();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {}
            }
        }

    }
}

@AllArgsConstructor
@NoArgsConstructor
class SimpleServerHandler implements Runnable {

    public static void main(String [] args){
        int port = 8080;
        SimpleServer server = new SimpleServer(port);
        Thread thread = new Thread(server);
        thread.start();
    }

    private Socket socket;

    @Override
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            out = new PrintWriter(this.socket.getOutputStream(), true);
            while (true) {
                String body = in.readLine();
                if (body == null) {
                    break;
                }
                System.out.println("Receive : " + body);
                out.println("Hello " + body);
            }
        } catch (Exception e) {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
            }
            if (this.socket != null) {
                try {
                    this.socket.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
                this.socket = null;
            }
        }
    }
}
